import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import { removeToken } from "@/utils/localStorage";
import {
  getAllUserApi,
  addOrUpdateUserApi,
  deleteUserApi,
  bulkDeleteUserApi,
  SelectKey,
} from "@/apis/acl/user";
import { MsgEnum, AclEnum, curriedFn } from "../.";
import type { IUserBase } from "@/apis/acl/user/type";
import type { IPermission } from "@/apis/acl/menu/type";
import { dateFormat } from "@/utils/tools";
import usePermissionStore from "@/store/modules/permission";
import { handlePermissions, listToTree } from "@/utils/tools";

const msg = curriedFn(AclEnum.user);

/**
 * 用户仓库
 */
const useUserStore = defineStore("userStore", {
  state: (): {
    /** table数据数组 */
    tableData: IUserBase[];
    /** 登录用户详情 */
    signUserDetail: IUserBase;
    /** 是否加载中 */
    loading: boolean;
    /** 当前页码 */
    currentPage: number;
    /** 每页显示条数 */
    pageSize: number;
    /** 总条数 */
    totalItem: number;
    /** 查询的key值；username|name */
    key: SelectKey;
    /** 查询的val值 */
    val: string;
    /** 权限数组结构 */
    constantPermissions: IPermission[];
  } => {
    return {
      tableData: [],
      signUserDetail: { name: "" },
      constantPermissions: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      totalItem: 20,
      key: SelectKey.name,
      val: "",
    };
  },
  actions: {
    /**
     * 根据查询值（页码，单页数量，查询key:value值）获取用户集合
     * @param pager
     * @returns
     */
    async getAllUser(pager = 1) {
      this.loading = true;
      try {
        const res = await getAllUserApi(
          pager,
          this.pageSize,
          this.key,
          this.val
        );
        if (res.code === 200) {
          if (!res.data.data) return;
          this.tableData = res.data.data?.map(item => {
            return {
              ...item,
              createdAt: dateFormat(item.createdAt!),
              updatedAt: dateFormat(item.updatedAt!),
            };
          });
          //获取分页数据
          this.totalItem = res.data.meta?.totalItems as number;
          this.currentPage = res.data.meta?.currentPage as number;
          this.pageSize = res.data.meta?.itemPerPage as number;
          ElMessage(msg(MsgEnum.get));
        }
      } catch (error: any) {
        ElMessage.error(error.message);
      } finally {
        this.loading = false;
      }
    },

    /**
     * 根据账号名称获取用户详情
     * @param username 账号名称，具有唯一性
     */
    async getUserDetailByUsername(username: string) {
      if (this.tableData.length === 0) {
        await this.getAllUser();
      }
      this.signUserDetail = this.tableData.find(
        item => item.username === username
      )!;
      const permissionStore = usePermissionStore();
      if (permissionStore.permissionList.length === 0) {
        await permissionStore.getPermissionList();
      }
      this.constantPermissions = [...permissionStore.permissionList];
    },

    async addOrUpdateUser(user: IUserBase) {
      this.loading = true;
      try {
        const res = await addOrUpdateUserApi(user);
        if (res.code === 200) {
          await this.getAllUser(user._id ? this.currentPage : 1);
          ElMessage.success(user._id ? msg(MsgEnum.update) : msg(MsgEnum.add));
        }
      } catch (error: any) {
        ElMessage.error(error.message);
      } finally {
        this.loading = false;
      }
    },
    async deleteUser(id: string) {
      this.loading = true;
      try {
        const res = await deleteUserApi(id);
        if (res.code === 200) {
          await this.getAllUser(
            this.tableData.length > 1
              ? this.currentPage
              : this.currentPage === 1
              ? 1
              : this.currentPage - 1
          );
          ElMessage.success(msg(MsgEnum.delete));
        }
      } catch (error: any) {
        ElMessage.error(error.message);
      } finally {
        this.loading = false;
      }
    },
    async bulkDeleteUser(ids: string[]) {
      this.loading = true;
      try {
        const res = await bulkDeleteUserApi(ids);
        if (res.code == 200) {
          await this.getAllUser(
            this.tableData.length > 1
              ? this.currentPage
              : this.currentPage === 1
              ? 1
              : this.currentPage - 1
          );
          ElMessage.success(msg(MsgEnum.delete));
        }
      } catch (error: any) {
        ElMessage.error(error.message);
      } finally {
        this.loading = false;
      }
    },
    userLogout() {
      // 登出逻辑
      removeToken();
    },
  },
  getters: {
    /** 根据数据库保存的perIds值生成登录用户权限树数组结构 */
    signUserPermissionTrees: state => {
      let perList = handlePermissions(
        state.constantPermissions,
        state.signUserDetail.permissionIds!
      );
      return listToTree(perList);
    },
  },
});

export default useUserStore;
